package pl.edu.kassiopeia.repository.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

@Service
public class PluginJarServiceImpl implements PluginJarService{
	private final Logger logger = Logger.getLogger(getClass());

	@Override
	public String getPluginXml(byte[] f) throws IOException {
		logger.info("Getting plugin.xml from the plugin jar file");
		File file = new File("tmp");
		OutputStream out;
		ZipFile zipFile;
		try {
			out = new FileOutputStream(file);
			out.write(f);
			zipFile = new ZipFile(file);
		} catch (IOException e) {
			logger.error("Couldn't create temporary file for storing " +
					"plugin jar file; logged and rethrown ", e);
			throw e;
		}

		ZipEntry entry = zipFile.getEntry("META-INF/plugin.xml");
		
		InputStream in;
		try {
			in = zipFile.getInputStream(entry);
			BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			StringBuffer sb = new StringBuffer();
			String str;
			while((str = br.readLine()) != null){
				sb.append(str);
			}
			return sb.toString();
		} catch (IOException e) {
			logger.error("Plugin has invalid plugin.xml file or " +
					"stored in wrong location; logged and rethrown", e);
			throw e;
		}
	}

}
